import Overlay from 'ol/Overlay';
import { Group as LayerGroup, Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import { water_factory_data } from '../components/List/水厂点位list'
import { dataListdata } from '../components/List/原水点位'
import { water_source_data } from '../components/List/water_source'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import { Icon, Style, Text, Fill } from 'ol/style'
import { advancedAllList } from '../http/http'
import { dataSource } from '../components/List/advancedAllList'
import { proj4Epsg } from '../tools/proj4_EPSG'
import { createApp, h } from 'vue';
import PopUpSc from '../components/bubblePop/bubblePop-up.vue';
import PopUpSk from '../components/bubblePop/bubblePop_Sk.vue';
import PopUpGw from '../components/bubblePop/bubblePop_Gw.vue';
import bus from '../tools/eventBus'


// 获取文件所在地址
const pathName = window.document.location.pathname;
const pathUrl = pathName.substring(0, pathName.lastIndexOf('/'));

// 依据geom信息定位
function flyToByGeom(geom, duration = 1200, zoom = 16) {
  // let pt = centerByParams(geom.getExtent())
  // console.log(geom, 'geom');
  let theMap = window.Pipe_Map
  if (geom && theMap) {
    flyTo(geom, theMap, duration, zoom)
  }
}
// 定位移动速度
function flyTo(lnglat, map, duration, zoom) {
  //duration 用于设置移动的速度
  duration = duration || 2000
  //zoom是地图的视野
  zoom = zoom || 14
  let currt = map.getView().getZoom()
  //这里给动画设置一个初始值
  map.getView().animate({
    center: lnglat,
    duration,
  })
  // //这里是关键代码
  map.getView().animate(
    //动画开始时
    {
      zoom: currt,
      duration: duration / 2,
    },
    //动画结束时
    {
      zoom: 18,
      duration: duration / 2,
    }
  )
}

// // 创建气泡方法
// function OverLayer(list) {
//   console.log('list', list);

//   list.forEach(createBubble);
// }

// function createBubble(data) {
//   const geom = [data.x, data.y]
//   let lonlat = proj4Epsg(geom)
//   // <div>${data.title}</div>
//   // <div>进水浊度：<span>${data.yali}</span>NTU</div>
//   // <div>进水ph：<span>${data.ph}</span></div>
//   // <div>进水压力：<span>${data.yali}</span>MPa</div>
//   const bubbleContent = document.createElement('div');
//   bubbleContent.className = 'custom-bubble';
//   bubbleContent.innerHTML = `
//   <div>所在位置：<span>${data.x}</span></div>
//   `;
//   document.body.appendChild(bubbleContent);
//   const bubble = new Overlay({
//     element: bubbleContent,
//     positioning: 'center-center',
//     stopEvent: false
//   });

//   let position = [lonlat[0], lonlat[1]];
//   bubble.setPosition(position);
//   window.Pipe_Map.addOverlay(bubble);
//   // bubblePositions.push({ position, bubble });
// }



// 创建气泡
function OverLayer(list, type, data = []) {
  console.log(type.name == '管网' && !type.value);

  // if (type.name == '管网' && !type.value) {
  //   console.log('打印了');

  // }
  list.forEach((item) => {
    createBubble(item, type.name, data)
  });
}

let water = false
let flow = false
let pressure = false

// 气泡组件
function createBubble(data, type, dataTcSj) {
  // alert(type)
  const geom = [data.x, data.y];
  let lonlat = []
  lonlat = type == '管网' ? geom : proj4Epsg(geom); // 管网数据经纬度不需要转换
  // 创建 PopUpSc 组件实例

  switch (type) {
    case '水厂':
      const app = createApp({
        render() {
          return h(PopUpSc, { data, position: { x: data.x, y: data.y } });
        }
      });
      // 挂载组件到一个新的 DOM 元素上
      const bubbleContent = document.createElement('div');
      app.mount(bubbleContent);
      const bubble = new Overlay({
        element: bubbleContent,
        positioning: 'center-center',
        stopEvent: false
      });
      let position = [lonlat[0], lonlat[1]];
      bubble.setPosition(position);
      window.Pipe_Map.addOverlay(bubble);
      break;
    case '水库':
      const dataTcSj1 = RealTimeFn(data, dataTcSj)
      const appSk = createApp({
        render() {
          return h(PopUpSk, { data, dataTcSj1, position: { x: data.x, y: data.y } });
        }
      });
      // 挂载组件到一个新的 DOM 元素上
      const bubbleContentSk = document.createElement('div');
      appSk.mount(bubbleContentSk);
      const bubbleSk = new Overlay({
        element: bubbleContentSk,
        positioning: 'center-centerSk',
        stopEvent: false
      });
      let positionSk = [lonlat[0], lonlat[1]];
      bubbleSk.setPosition(positionSk);
      window.Pipe_Map.addOverlay(bubbleSk);
      break;
    case '管网':
      console.log('触发了吗')
      // 通过鼠标缩放控制气泡显隐
      window.Pipe_Map.on('moveend', moveendTc)
      break;
  }

  // TypeSwitch
  bus.on('TypeSwitch', ({ item }) => {
    console.log(item.name, item.value, '232323');

    if (item.name == '管网' && item.value == false) {
      window.Pipe_Map.removeEventListener('moveend', moveendTc);
      window.Pipe_Map.removeEventListener('moveend', moveendDw)
    }
  })

  // 通过鼠标缩放控制气泡显隐
  function moveendTc() {
    console.log('触发了吗11')
    const bubbles11 = document.querySelectorAll('.pop-upGw1');
    const bubbles12 = document.querySelectorAll('.pop-upGw2');
    const bubbles13 = document.querySelectorAll('.pop-upGw3');
    const aaa = bubbles11.length == 19
    const bbb = bubbles12.length == 20
    const ccc = bubbles13.length == 17

    let zoom = window.Pipe_Map.getView().getZoom()
    if (data.stage == '1' && !aaa) {
      createOverlay(data)
    } else if (zoom >= 13 && data.stage == '2' && !bbb) {
      createOverlay(data)

    } else if (zoom >= 16 && data.stage == '3' && !ccc) {
      createOverlay(data)
    }
    else if (zoom <= 13 && data.stage == '2') {
      cleanBubbleGw2()
    } else if (zoom <= 16 && data.stage == '3') {
      cleanBubbleGw3()
    }
  }

  // 管网气泡
  function createOverlay(data) {
    const appGw = createApp({
      render() {
        return h(PopUpGw, { data, position: { x: data.x, y: data.y } });
      }
    });

    // 挂载组件到一个新的 DOM 元素上
    const bubbleContentGw = document.createElement('div');
    appGw.mount(bubbleContentGw);
    const bubbleGw = new Overlay({
      element: bubbleContentGw,
      positioning: 'center-centerGw',
      stopEvent: false
    });
    let positionGw = [lonlat[0], lonlat[1]];
    bubbleGw.setPosition(positionGw);
    window.Pipe_Map.addOverlay(bubbleGw);
  }

  // 水库点位信息和实时数据做关联
  function RealTimeFn(data, dataTcSj) {
    let initData = {}
    dataTcSj.forEach((item) => {
      if (item.sk_name == data.name) {
        initData = {
          ...data, ...item
        }
      }
    })
    return initData
  }
}

// 清除水厂气泡方法
function cleanBubbleSc() {
  // 清除所有名为 'custom-bubble' 的元素
  const bubbles = document.querySelectorAll('.pop-upSc');
  bubbles.forEach(bubble => bubble.remove());
}

// 清除水库气泡方法
function cleanBubbleSk() {
  // 清除所有名为 'custom-bubble' 的元素
  const bubbles = document.querySelectorAll('.pop-upSk');
  bubbles.forEach(bubble => bubble.remove());
}

// 清除管网气泡方法 stage1
function cleanBubbleGw() {
  // 清除所有名为 'custom-bubble' 的元素
  const bubbles = document.querySelectorAll('.pop-upGw1');
  bubbles.forEach(bubble => bubble.remove());
}
// 清除管网气泡方法 stage2
function cleanBubbleGw2() {
  // 清除所有名为 'custom-bubble' 的元素
  const bubbles = document.querySelectorAll('.pop-upGw2');
  bubbles.forEach(bubble => bubble.remove());
}
// 清除管网气泡方法 stage3
function cleanBubbleGw3() {
  // 清除所有名为 'custom-bubble' 的元素
  const bubbles = document.querySelectorAll('.pop-upGw3');
  bubbles.forEach(bubble => bubble.remove());
}


// 判断是否有图层
function findLayerByParam(map, layerVal, layerKey = 'id') {
  let toLyr = null
  map.getLayers().forEach((item) => {
    if (item instanceof LayerGroup) {
      item.getLayers().forEach((t) => {
        if (t.get(layerKey) === layerVal) {
          toLyr = t
        }
      })
    } else {
      if (item.get(layerKey) === layerVal) {
        toLyr = item
      }
    }
  })
  return toLyr
}

/*
  水厂点位 
  水厂入参conditions: {
    waterworks: null
  }
*/

async function IncreaseWater(result) {
  const vectorLayer3 = getHightlightLayer()
  result.forEach((item) => {
    const geom = [item.x, item.y]
    let xy = proj4Epsg(geom)
    const a = new Feature({
      geometry: new Point(
        [xy[0], xy[1]],
        [item.prjno, 'waterPlant', item.name]
      ),
    })

    // 水厂icon样式
    a.setStyle(
      new Style({
        image: new Icon({
          src: pathUrl + '/icon/Sc@3x.png',
          // size: [10, 10],
          scale: 0.3,
        }),
        text: new Text({
          text: item.name,
          offsetY: 20, // 调整文本位置，使其显示在图标下方
          textAlign: 'center', // 文本水平居中
          font: '10px sans-serif', // 字体样式
          fill: new Fill({ color: 'black' }), // 文本颜色
        }),
      })
    )
    // 为每个要素添加点击事件监听器
    vectorLayer3.getSource().addFeature(a)
  })
  window.Pipe_Map.addLayer(vectorLayer3)
}

// 水库点位
function IncreaseWater2(result) {
  const vectorLayer2 = getHightlightLayer2()
  result.forEach((v) => {
    var p = new Feature({
      geometry: new Point(
        [v.lon, v.lat],
        [v.SmUserID, v.name,]
      ),
    })
    // 原水icon样式
    p.setStyle(
      new Style({
        image: new Icon({
          src: pathUrl + '/icon/Sk@3x.png',
          // size: [10, 10],
          scale: 0.3,
        }),
        text: new Text({
          text: v.name,
          offsetY: 20, // 调整文本位置，使其显示在图标下方
          textAlign: 'center', // 文本水平居中
          font: '10px sans-serif', // 字体样式
          fill: new Fill({ color: 'black' }), // 文本颜色
        }),
      })
    )

    // 为每个要素添加点击事件监听器
    vectorLayer2.getSource().addFeature(p)
  })
  window.Pipe_Map.addLayer(vectorLayer2)
}

var resultData = []
// 管网点位
function IncreaseWater1(result) {
  resultData = result
  // 监听地图的缩放事件
  window.Pipe_Map.on('moveend', moveendDw)

}

// 通过鼠标滑动控制点位显隐
function moveendDw() {
  var vectorLayer1 = getHightlightLayer1()
  var vectorLayer2_2 = getHightlightLayer2_2()
  var vectorLayer3 = getHightlightLayer3()
  let zoom = window.Pipe_Map.getView().getZoom()
  // 管网点位
  resultData.forEach((item) => {
    if (item.stage == '1') {
      resultItem(item, vectorLayer1);
    } else if (zoom >= 13 && item.stage == '2') {
      resultItem(item, vectorLayer2_2);
    } else if (zoom >= 16 && item.stage == '3') {
      resultItem(item, vectorLayer3);
    } else if (zoom <= 13 && item.stage == '2') {
      vectorLayer2_2.getSource().clear();
    } else if (zoom <= 16 && item.stage == '3') {
      vectorLayer3.getSource().clear();
    }
  })

}

// 管网数据点位
function resultItem(item, vectorLayer1) {
  const geom = [item.x, item.y]
  let xy = geom  //  proj4Epsg(geom) - 投影坐标系转换经纬度
  const p = new Feature({
    geometry: new Point(
      [xy[0], xy[1]],
      [item, item.dataType, item.name]
    ),
  })
  // 管网icon样式
  p.setStyle(
    new Style({
      image: new Icon({
        src: pathUrl + pipeNetwork(item.dataType),
        scale: 0.3,
      }),
      text: new Text({
        // text: item.name,
        offsetY: 20, // 调整文本位置，使其显示在图标下方
        textAlign: 'center', // 文本水平居中
        font: '10px sans-serif', // 字体样式
        fill: new Fill({ color: 'black' }), // 文本颜色
      }),
    })
  )

  // 添加
  vectorLayer1.getSource().addFeature(p)
}

// 管网图标类型区分
function pipeNetwork(type) {
  switch (type) {
    case 'flowmeasure':
      return '/icon/Lljcd@3x.png'
    case 'pressuretap':
      return '/icon/Yljcd@3x.png'
    case 'waterparticle':
      return '/icon/Szjcd@3x.png'
  }
}



// 管网点位数据
// function resultData() {

// }

// 获取图层没有则创建-管网
function MapLayer(layerId = 'MapId') {
  let theMap = window.Pipe_Map
  let to = findLayerByParam(theMap, layerId)
  if (to) {
    return to
  }
  // 不存在，则创建目标图层
  let toLayer = new VectorLayer({
    id: layerId,
    source: new VectorSource(),
    zIndex: 999,
  })
  theMap.addLayer(toLayer)
  return toLayer
}

// 获取图层没有则创建-管网--stage1
function getHightlightLayer1(layerId = 'layerId1') {
  let theMap = window.Pipe_Map
  let to = findLayerByParam(theMap, layerId)
  if (to) {
    return to
  }
  // 不存在，则创建目标图层
  let toLayer = new VectorLayer({
    id: layerId,
    source: new VectorSource(),
    zIndex: 999,
  })
  theMap.addLayer(toLayer)
  return toLayer
}


// 获取图层没有则创建-管网--stage2
function getHightlightLayer2_2(layerId = 'layerId2_2') {
  let theMap = window.Pipe_Map
  let to = findLayerByParam(theMap, layerId)
  if (to) {
    return to
  }
  // 不存在，则创建目标图层
  let toLayer = new VectorLayer({
    id: layerId,
    source: new VectorSource(),
    zIndex: 999,
  })
  theMap.addLayer(toLayer)
  return toLayer
}

// 获取图层没有则创建-管网--stage3
function getHightlightLayer3(layerId = 'layerId3_3') {
  let theMap = window.Pipe_Map
  let to = findLayerByParam(theMap, layerId)
  if (to) {
    return to
  }
  // 不存在，则创建目标图层
  let toLayer = new VectorLayer({
    id: layerId,
    source: new VectorSource(),
    zIndex: 999,
  })
  theMap.addLayer(toLayer)
  return toLayer
}


// 获取图层没有则创建
function getHightlightLayer2(layerId = 'layerId2') {
  let theMap = window.Pipe_Map
  let to = findLayerByParam(theMap, layerId)
  if (to) {
    return to
  }
  // 不存在，则创建目标图层
  let toLayer = new VectorLayer({
    id: layerId,
    source: new VectorSource(),
    zIndex: 999,
  })
  theMap.addLayer(toLayer)
  return toLayer
}

// 获取图层没有则创建-水厂
function getHightlightLayer(layerId = 'layerId3') {
  let theMap = window.Pipe_Map
  let to = findLayerByParam(theMap, layerId)
  if (to) {
    return to
  }
  // 不存在，则创建目标图层
  let toLayer = new VectorLayer({
    id: layerId,
    source: new VectorSource(),
    zIndex: 999,
  })
  theMap.addLayer(toLayer)
  return toLayer
}

// 清除管网图层--stage1
function clearHighlights1() {
  // window.Pipe_Map.off('moveend');
  let toLayer1 = getHightlightLayer1()
  if (!toLayer1) {
    return
  }
  toLayer1.getSource().clear()
}
// 清除管网图层--stage2
function clearHighlights2_2() {
  let toLayer2 = getHightlightLayer2_2()
  if (!toLayer2) {
    return
  }
  toLayer2.getSource().clear()
}
// 清除管网图层--stage3
function clearHighlights3() {
  let toLayer3 = getHightlightLayer3()
  if (!toLayer3) {
    return
  }
  toLayer3.getSource().clear()
}

// 清除水库图层
function clearHighlights2() {
  let toLayer2 = getHightlightLayer2()
  if (!toLayer2) {
    return
  }
  toLayer2.getSource().clear()
}

// 清除水厂图层
function clearHighlights() {
  let toLayer3 = getHightlightLayer()
  if (!toLayer3) {
    return
  }
  toLayer3.getSource().clear()
}

export {
  flyToByGeom,
  OverLayer,
  cleanBubbleSc,
  cleanBubbleSk,
  cleanBubbleGw,
  clearHighlights1,
  clearHighlights2_2,
  clearHighlights3,
  clearHighlights2,
  clearHighlights,
  getHightlightLayer1,
  getHightlightLayer2,
  getHightlightLayer,
  IncreaseWater2,
  IncreaseWater,
  IncreaseWater1,
  MapLayer
}